<template>
  <div class="problem-list">
    <h1 class="page-title">{{ APP_CONFIG.title }}</h1>
    
    <div class="search-container">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery"
          placeholder="搜索题目..."
          @keyup.enter="handleSearch"
        >
        <button @click="handleSearch">
          <span class="search-icon">🔍</span>
        </button>
      </div>
    </div>

    <div class="difficulty-filter">
      <el-radio-group v-model="selectedDifficulty" @change="handleSearch">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button 
          v-for="diff in DIFFICULTIES" 
          :key="diff"
          :label="diff"
        >
          {{ DIFFICULTY_MAP[diff] }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <el-table
      :data="problems"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column label="#" width="80">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题">
        <template #default="{ row }">
          <el-link
            type="primary"
            @click="handleProblemClick(row.id)"
          >
            {{ row.title }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="source" label="来源" />
      <el-table-column prop="pass_rate" label="通过率" width="120">
        <template #default="{ row }">
          {{ row.pass_rate.toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column prop="difficulty" label="难度" width="120">
        <template #default="{ row }">
          <el-tag
            :type="getDifficultyType(row.difficulty)"
            effect="plain"
          >
            {{ DIFFICULTY_MAP[row.difficulty] }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import problemApi from '../api/problem'
import { APP_CONFIG } from '../constants/config'
import type { Problem } from '../api/problem'

const DIFFICULTIES = ['Easy', 'Medium', 'Hard']
const DIFFICULTY_MAP = {
  'Easy': '简单',
  'Medium': '中等',
  'Hard': '困难'
}

const router = useRouter()
const searchQuery = ref('')
const selectedDifficulty = ref('')
const problems = ref<Problem[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const getDifficultyType = (difficulty: string) => {
  const types = {
    'Easy': 'success',
    'Medium': 'warning',
    'Hard': 'danger'
  }
  return types[difficulty as keyof typeof types] || 'info'
}

const fetchProblems = async () => {
  loading.value = true
  try {
    const data = await problemApi.getList({
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchQuery.value,
      difficulty: selectedDifficulty.value || undefined,
      ordering: '-create_time'
    })
    problems.value = data

  } catch (error) {
    ElMessage.error('获取题目列表失败')
    console.error('Failed to fetch problems:', error)
  } finally {
    loading.value = false
  }
  try {
    const count = await problemApi.getCount({
      search: searchQuery.value,
      difficulty: selectedDifficulty.value || undefined,
    })
    total.value = count
  } catch (error) {
    ElMessage.error('获取题目数量失败')
    console.error('Failed to fetch problem count:', error)
  }
}
const handleProblemClick = (problemId: number) => {
  router.push(`/problem/${problemId}`)
}

const handleSearch = () => {
  currentPage.value = 1
  fetchProblems()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchProblems()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchProblems()
}

onMounted(() => {
  fetchProblems()
})
</script>

<style scoped>
.problem-list {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  text-align: center;
  margin-bottom: 30px;
  color: var(--el-text-color-primary);
}

.search-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.search-box {
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 500px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.search-box input {
  flex: 1;
  padding: 8px 12px;
  border: none;
  outline: none;
  font-size: 14px;
}

.search-box button {
  padding: 8px 16px;
  background: none;
  border: none;
  border-left: 1px solid #dcdfe6;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-box button:hover {
  background-color: #f5f7fa;
}

.search-icon {
  font-size: 16px;
}

.difficulty-filter {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
